﻿Public Class NewCasesCreationForm

    Public ThePeriod As Integer
    Public TheCaseID As String
    Public TheCaseName As String
    Public TheNotes As String
    Public Invisible As Boolean
    Public TheFieldCode As Integer
    Public TheFieldOrder As Integer
    Public TheFieldName As String

    Dim FireEvents As Boolean = False
    Dim NewCaseCreated As Boolean = False
    Dim CancelValidation As Boolean = False


    Private Sub NewCasesCreationForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        LoadPeriodBox()

    End Sub

    Private Sub LoadPeriodBox()

        Dim SQL As String

        SQL = "Select * from Periods"

        If LoadComboBox(PeriodBox, SQL, "Period_ID", "Period_Name") = False Then
            MessageBox.Show("There has been an error loading the cases, please contact The Store administrator", "Period Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
        End If

        FireEvents = True

        PeriodBox.SelectedValue = GlobalSettings.CurrentPeriodID

    End Sub

    Private Sub PeriodBox_SelectedValueChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PeriodBox.SelectedIndexChanged

        If FireEvents = False Then Exit Sub

        ThePeriod = PeriodBox.SelectedValue

        LoadCaseGrid()

    End Sub

    Private Sub LoadCaseGrid()

        Dim TheWidth As Integer

        With CaseGrid

            Dim sql As String
            Dim TheData As DataView

            sql = "Select * from Modelling_Case_Datasets where Period_ID = " & ThePeriod & " Order By Description"

            TheData = LoadDataView(sql)

            'This fires the selected index change which calls LoadFieldGrid
            .DataSource = TheData

            'Sort Formats Out
            .AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells

            If .Columns("Description").Width < 400 Then
                .Columns("Description").MinimumWidth = 400
                TheWidth = 400
            Else
                TheWidth = .Columns("Description").Width
            End If

            .Width = TheWidth
            SplitContainer.SplitterDistance = TheWidth

            If TheData.Count = 0 Then
                ClearFieldPanel()
                CaseDeleteButton.Enabled = False
                Exit Sub
            End If
            
            CaseGrid.Rows(0).Selected = True
            CaseDeleteButton.Enabled = True

        End With

    End Sub

    Private Sub CaseGrid_SelectionChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CaseGrid.SelectionChanged

        With CaseGrid

            If .SelectedRows.Count = 0 Then Exit Sub

            TheCaseID = Trim(.Item("DataCut_ID", .SelectedRows(0).Index).Value.ToString)
            TheCaseName = Trim(.Item("Description", .SelectedRows(0).Index).Value.ToString)
            TheNotes = Trim(.Item("Notes", .SelectedRows(0).Index).Value.ToString)

            If .Item("Invisible", .SelectedRows(0).Index).Value = 1 Then
                Invisible = True
            Else
                Invisible = False
            End If

            CaseIDBox.Text = TheCaseID
            CaseIDBox.Enabled = False
            CaseNameBox.Text = TheCaseName
            NotesBox.Text = TheNotes
            InvisibleBox.Checked = Invisible
            FieldPanel.Show()

            'Load field grid and select 1st Row
            LoadFieldGrid(0)

        End With

    End Sub

    Public Sub LoadFieldGrid(ByVal ReloadRow As Integer)

        'If FireEvents = False Then Exit Sub
        If CaseGrid.SelectedRows.Count = 0 Then Exit Sub

        Dim sql As String
        Dim TheData As DataView

        sql = "Select t.*, t.Field_Name as [Field Name], l.Table_Description as [Table Type],  d.Type_Description as [Data Type], t.Formula as [Field Type], t.DisplaySQL as [Calculation] " & _
              "from Modelling_Case_Templates t " & _
              "Left Outer Join Modelling_TableList l on (t.Modelling_Table=l.Table_Name) " & _
              "Left Outer Join Modelling_Case_DataTypes d on (d.type=t.type) " & _
              "where DataCut_ID = '" & TheCaseID & "' and Period_ID = " & ThePeriod & _
              " Order By Field_Order "

        TheData = LoadDataView(sql)

        If TheData.Count = 0 Then
            FieldDeleteButton.Enabled = False
            FieldEditButton.Enabled = False
            UpButton.Enabled = False
            DownButton.Enabled = False
            FieldGrid.DataSource = Nothing
            Exit Sub
        ElseIf TheData.Count = 1 Then
            UpButton.Enabled = False
            DownButton.Enabled = False
        Else
            UpButton.Enabled = True
            DownButton.Enabled = True
        End If

        FieldGrid.DataSource = TheData
        FieldDeleteButton.Enabled = True
        FieldEditButton.Enabled = True
        FieldGrid.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells
        UpdateVarValues()

    End Sub

    Private Sub CloseButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)

        Me.Close()

    End Sub

    Public Sub ClearFieldPanel()

        CaseIDBox.Clear()
        CaseNameBox.Clear()
        NotesBox.Clear()
        InvisibleBox.Checked = False
        FieldGrid.DataSource = Nothing
        FieldPanel.Hide()

    End Sub

    Function CreateID() As String

        Dim d, m, y, mm, h, s, ms, t As String

        d = Now.Day
        m = Now.Month
        y = Now.Year

        If d.Length <> 2 Then
            d = "0" & d
        End If

        If m.Length <> 2 Then
            m = "0" & m
        End If

        mm = Now.Minute

        h = Now.Hour

        s = Now.Second

        ms = Now.Millisecond

        If mm.Length <> 2 Then
            mm = "0" & mm
        End If

        If h.Length <> 2 Then
            h = "0" & h
        End If

        If s.Length <> 2 Then
            s = "0" & s
        End If

        Select Case ms.Length
            Case 1
                ms = "000" & ms
            Case 2
                ms = "00" & ms
            Case 3
                ms = "0" & ms
        End Select

        t = "CASEIDNUMBER00000" & d & m & y & m & h & s & ms
        CreateID = t
    End Function

    Private Sub CaseAddButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CaseAddButton.Click

        ClearFieldPanel()

        FieldPanel.Show()

        CaseIDBox.Text = CreateID()
        TheCaseID = CaseIDBox.Text
        CaseIDBox.Enabled = False
        CaseNameBox.Select()

        NewCaseCreated = True
        CancelValidation = False

    End Sub


    Private Sub CaseDeleteButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CaseDeleteButton.Click

        If CaseGrid.SelectedRows.Count = 0 Then Exit Sub

        If MessageBox.Show("Deleting this case will remove it permanently from the database, are you sure you wish to continue?", "Warning", _
                           MessageBoxButtons.YesNo, MessageBoxIcon.Warning) = Windows.Forms.DialogResult.No Then
            Exit Sub
        End If

        CancelValidation = True

        Dim sql As String

        'sql = "Delete from Modelling_Case_Templates where DataCut_ID = '" & TheCaseID & "' and Period_ID = " & ThePeriod

        'RunNonQuery(sql)

        sql = "Delete from Modelling_Case_Datasets where DataCut_ID = '" & TheCaseID & "' and Period_ID = " & ThePeriod

        RunNonQuery(sql)

        MessageBox.Show("Your case has been deleted", "Delete Confirmed", MessageBoxButtons.OK, MessageBoxIcon.Information)

        LoadCaseGrid()


    End Sub

    Private Sub NewCasesCreationForm_Activated(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Activated

        'Load field grid and select 1st Row
        LoadFieldGrid(0)

    End Sub

    Private Sub FieldDeleteButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles FieldDeleteButton.Click

        Dim sql As String

        With FieldGrid

            If .SelectedRows.Count = 0 Then Exit Sub
            GetCurrentRow()


        End With

        If MessageBox.Show("Are you sure you want to delete this field?", "Confirm Delete", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) = Windows.Forms.DialogResult.No Then
            Exit Sub
        End If

        sql = "Delete from Modelling_Case_Templates where DataCut_ID = '" & TheCaseID & "' and Period_ID = " & ThePeriod & " and Field_Code = " & TheFieldCode

        RunNonQuery(sql)


        LoadFieldGrid(0)


    End Sub


    Private Sub FieldEditButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles FieldEditButton.Click

        NewCasesAdminForm.WhoCalled = "EditField"
        NewCasesAdminForm.ShowDialog()

    End Sub

    Private Sub ToolAddButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolAddButton.Click

        NewCasesAdminForm.WhoCalled = "AddField"
        NewCasesAdminForm.ShowDialog()

    End Sub

    Private Sub FieldGrid_CellEnter(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles FieldGrid.CellEnter

        UpdateVarValues()

    End Sub

    Public Sub UpdateVarValues()

        If FieldGrid.CurrentRow Is Nothing Then Exit Sub

        If FieldGrid.SelectedRows.Count = 0 Then Exit Sub

        With FieldGrid

            If .CurrentRow.Index = -1 Then Exit Sub

            TheFieldCode = .Item("Field_Code", .SelectedRows(0).Index).Value
            TheFieldOrder = .Item("Field_Order", .SelectedRows(0).Index).Value
            TheFieldName = .Item("Field Name", .SelectedRows(0).Index).Value

        End With
    End Sub

    Private Sub CloseButton_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CloseButton.Click
        Me.Close()
    End Sub

    Private Sub InvisibleBox_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles InvisibleBox.CheckedChanged

        If FireEvents = False Then Exit Sub

        Dim Value As Integer
        Dim sql As String

        If InvisibleBox.CheckState = False Then
            Value = 0
            Invisible = False
        Else
            Value = 1
            Invisible = True
        End If

        sql = "Update Modelling_Case_Datasets Set Invisible = " & Value & " Where DataCut_ID = '" & TheCaseID & "' and Period_ID = " & ThePeriod

        Try
            RunNonQuery(sql)
        Catch ex As Exception
            MessageBox.Show("There has been an error, please contact The Store Administrator", "Error", MessageBoxButtons.AbortRetryIgnore, MessageBoxIcon.Error)
            Exit Sub
        End Try

    End Sub

    Private Sub CaseNameBox_Validating(ByVal sender As System.Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles CaseNameBox.Validating

        If FireEvents = False Then Exit Sub
        If CancelValidation = True Then Exit Sub

        If CaseNameBox.TextLength = 0 Then
            MessageBox.Show("Please enter a name for your Case", "Case Name", MessageBoxButtons.OK, MessageBoxIcon.Error)
            e.Cancel = True
            CaseNameBox.Select()
        End If

        Dim sql As String

        If NewCaseCreated = True Then
            sql = "Insert Into Modelling_Case_Datasets Values ('" & TheCaseID & "', " & ThePeriod & ", '" & CaseNameBox.Text.ToString & "' , '', 0)"
            NewCaseCreated = False
        Else
            sql = "Update Modelling_Case_Datasets Set Description = '" & CaseNameBox.Text & "' Where DataCut_ID = '" & TheCaseID & "' and Period_ID = " & ThePeriod
        End If

            Try
                RunNonQuery(sql)
            Catch ex As Exception
                MessageBox.Show("There has been an error, please contact The Store Administrator", "Error", MessageBoxButtons.AbortRetryIgnore, MessageBoxIcon.Error)
            e.Cancel = True
            Exit Sub
            End Try

        e.Cancel = False
        TheCaseName = CaseNameBox.Text

        'Update the Case Grid
        Dim ReloadMe As String
        ReloadMe = TheCaseID
        LoadCaseGrid()

        Dim r As DataGridViewRow
        With CaseGrid

            For Each r In .Rows
                If .Item("DataCut_ID", r.Index).Value.ToString = ReloadMe Then
                    ReloadMe = r.Index
                    .Rows(ReloadMe).Selected = True
                    Exit Sub
                End If
            Next

        End With


    End Sub

    Private Sub NotesBox_Validating(ByVal sender As System.Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles NotesBox.Validating

        If FireEvents = False Then Exit Sub

        Dim sql As String

        sql = "Update Modelling_Case_Datasets Set Notes = '" & NotesBox.Text & "' Where DataCut_ID = '" & TheCaseID & "' and Period_ID = " & ThePeriod

        Try
            RunNonQuery(sql)
        Catch ex As Exception
            MessageBox.Show("There has been an error, please contact The Store Administrator", "Error", MessageBoxButtons.AbortRetryIgnore, MessageBoxIcon.Error)
            e.Cancel = True
            Exit Sub
        End Try

        e.Cancel = False
        TheNotes = NotesBox.Text


    End Sub

    Private Function TheOrderCode(ByVal TheRow As Integer)

        With FieldGrid

            TheOrderCode = .Item("Field_Order", TheRow).Value

            Return TheOrderCode

        End With

    End Function

    Private Sub UpButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles UpButton.Click

        Dim sql As String

        Dim TheRow As Integer
        Dim NewOrderCode As Integer
        Dim OldOrderCode As Integer
        Dim ThisFieldCode As Integer
        Dim NextfieldCode As Integer

        If FieldGrid.SelectedRows.Count = 0 Then Exit Sub
        If FireEvents = False Then Exit Sub
        If FieldGrid.SelectedRows(0).Index = -1 Then Exit Sub
        If FieldGrid.SelectedRows(0).Index = 0 Then Exit Sub

        TheRow = FieldGrid.SelectedRows(0).Index

        NewOrderCode = TheOrderCode(TheRow - 1)
        OldOrderCode = TheOrderCode(TheRow)
        ThisFieldCode = FieldGrid.Item("Field_Code", TheRow).Value
        NextfieldCode = FieldGrid.Item("Field_Code", TheRow - 1).Value

        sql = "Update Modelling_Case_Templates Set Field_Order = " & NewOrderCode & " Where DataCut_ID = '" & TheCaseID & "' and Period_ID = " & ThePeriod & _
                " and Field_Code = " & ThisFieldCode

        RunNonQuery(sql)

        sql = "Update Modelling_Case_Templates Set Field_Order = " & OldOrderCode & " Where DataCut_ID = '" & TheCaseID & "' and Period_ID = " & ThePeriod & _
                " and Field_Code = " & NextfieldCode

        RunNonQuery(sql)

        LoadFieldGrid(0)
        FieldGrid.Rows(GetTheRow(ThisFieldCode, "Field_Code")).Selected = True
        UpdateVarValues()

    End Sub


    Private Sub DownButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DownButton.Click

        Dim sql As String

        Dim TheRow As Integer
        Dim NewOrderCode As Integer
        Dim OldOrderCode As Integer
        Dim ThisFieldCode As Integer
        Dim NextfieldCode As Integer

        If FireEvents = False Then Exit Sub
        If FieldGrid.SelectedRows.Count = 0 Then Exit Sub
        If FieldGrid.SelectedRows(0).Index = -1 Then Exit Sub

        TheRow = FieldGrid.SelectedRows(0).Index

        If TheRow = FieldGrid.Rows.Count - 1 Then Exit Sub

        NewOrderCode = TheOrderCode(TheRow + 1)
        OldOrderCode = TheOrderCode(TheRow)
        ThisFieldCode = FieldGrid.Item("Field_Code", TheRow).Value
        NextfieldCode = FieldGrid.Item("Field_Code", TheRow + 1).Value

        sql = "Update Modelling_Case_Templates Set Field_Order = " & NewOrderCode & " Where DataCut_ID = '" & TheCaseID & "' and Period_ID = " & ThePeriod & _
                " and Field_Code = " & ThisFieldCode

        RunNonQuery(sql)

        sql = "Update Modelling_Case_Templates Set Field_Order = " & OldOrderCode & " Where DataCut_ID = '" & TheCaseID & "' and Period_ID = " & ThePeriod & _
                " and Field_Code = " & NextfieldCode

        RunNonQuery(sql)

        LoadFieldGrid(0)
        FieldGrid.Rows(GetTheRow(ThisFieldCode, "Field_Code")).Selected = True
        UpdateVarValues()

    End Sub

    Private Sub CaseGrid_CellPainting(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellPaintingEventArgs) Handles CaseGrid.CellPainting

        'CaseGrid.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells

        With CaseGrid.Columns(e.ColumnIndex)

            If .Name <> "Description" Then
                .Visible = False
            Else
                .Visible = True
                .ReadOnly = True
            End If

        End With

    End Sub

    Private Sub FieldGrid_CellPainting(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellPaintingEventArgs) Handles FieldGrid.CellPainting

        With FieldGrid.Columns(e.ColumnIndex)

            If .Name = "Table Type" Or .Name = "Data Type" Or .Name = "Field Name" Or .Name = "Calculation" Or .Name = "Field Type" Then
                .Visible = True
                .ReadOnly = True
            Else
                .Visible = False
            End If

        End With

    End Sub

    Public Function GetTheRow(ByVal TheItem As String, ByVal TheColumn As String)

        GetTheRow = 0

        Dim r As DataGridViewRow

        With FieldGrid

            For Each r In .Rows
                If .Item(TheColumn, r.Index).Value.ToString = TheItem Then
                    GetTheRow = r.Index
                    Exit Function
                End If
            Next

        End With

    End Function

    Public Function GetCurrentRow()

        With FieldGrid
            If .SelectedRows.Count = 0 Then
                GetCurrentRow = -1 ' I think?
                Exit Function
            End If

            GetCurrentRow = .SelectedRows(0).Index
            Return GetCurrentRow
        End With

    End Function

    Private Sub FieldGrid_SelectionChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles FieldGrid.SelectionChanged

        UpdateVarValues()

    End Sub

    Private Sub FieldGrid_RowEnter(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles FieldGrid.RowEnter

        UpdateVarValues()

    End Sub
End Class